package logic

import (
	"context"
	"errors"
	"manuscript-service/model/model"
	"strconv"

	"manuscript-service/servicerpc/internal/svc"
	"manuscript-service/servicerpc/servicerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserAddLogic {
	return &UserAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserAddLogic) UserAdd(in *servicerpc.UserAddRequest) (*servicerpc.UserAddResponse, error) {
	// todo: add your logic here and delete this line

	var userCj model.User

	begin := model.DB.Begin()

	if err := userCj.UserCjAdd(begin, in.Title); err != nil {
		goods := model.Good{
			GoodName: strconv.FormatInt(in.GoodId, 10),
		}
		if err = goods.GoodsAdd(begin); err != nil {
			return nil, errors.New("不存在就创建")
			begin.Rollback()
		}

	}

	user := model.User{
		Title:  in.Title,
		Num:    int(in.Num),
		Image:  in.Image,
		GoodId: int(in.GoodId),
	}

	var usersCf model.User
	if err := usersCf.UsersCfAdd(begin, in.Title); err != nil {
		return nil, errors.New("商品不能重复")
		begin.Rollback()
	}

	if err := user.UserAdd(begin); err != nil {
		return nil, err
	}

	return &servicerpc.UserAddResponse{
		UserId: int64(user.ID),
	}, nil
}
